<template>
  <div class="search-form">
    <el-form ref="formRef" :model="formModel" :inline="true" class="form-container">
      <slot></slot>
      <el-form-item class="action-item">
        <div class="form-actions">
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
          <el-button 
            v-if="showExpand && formItems.length > collapsedCount" 
            type="text" 
            @click="toggleExpand"
          >
            {{ isExpanded ? '收起' : '展开' }}
            <el-icon class="expand-icon" :class="{ 'expanded': isExpanded }">
              <ArrowDown />
            </el-icon>
          </el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, provide, useSlots } from 'vue'
import { Search, Refresh, ArrowDown } from '@element-plus/icons-vue'

const props = defineProps({
  // 表单数据对象
  model: {
    type: Object,
    required: true
  },
  // 收起状态显示的表单项数量
  collapsedCount: {
    type: Number,
    default: 3
  },
  // 是否显示展开/收起按钮
  showExpand: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['search', 'reset'])

const formRef = ref(null)
const formModel = computed(() => props.model)
const isExpanded = ref(false)
const formItems = ref([])
const slots = useSlots()

// 搜索操作
const handleSearch = () => {
  emit('search', formModel.value)
}

// 重置操作
const handleReset = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  emit('reset')
}

// 切换展开/收起状态
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value
  updateFormItemsDisplay()
}

// 更新表单项的显示/隐藏状态
const updateFormItemsDisplay = () => {
  if (!props.showExpand || formItems.value.length <= props.collapsedCount) {
    formItems.value.forEach(item => {
      item.style.display = ''
    })
    return
  }

  formItems.value.forEach((item, index) => {
    if (index >= props.collapsedCount && !isExpanded.value) {
      item.style.display = 'none'
    } else {
      item.style.display = ''
    }
  })
}

// 提供上下文，让内部表单项可以获取展开状态
provide('searchFormExpanded', isExpanded)
provide('searchFormCollapsedCount', props.collapsedCount)

// 在挂载后获取所有的表单项并处理展开/收起状态
onMounted(() => {
  // 获取除操作按钮外的所有表单项
  const allItems = formRef.value?.$el.querySelectorAll('.el-form-item')
  formItems.value = Array.from(allItems).filter(item => !item.classList.contains('action-item'))
  
  // 初始化表单项的显示状态
  updateFormItemsDisplay()
})
</script>

<style scoped>
.search-form {
  width: 100%;
}

.form-container {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}

.form-actions {
  display: flex;
  align-items: center;
  white-space: nowrap;
}

.action-item {
  margin-left: auto;
  margin-right: 0;
}

.expand-icon {
  transition: transform 0.3s;
}

.expanded {
  transform: rotate(180deg);
}
</style> 